package com.example.minademo.mina;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
//用户长连接session的管理类
public class UserSessionManager {

    private static UserSessionManager mInstance;
    private UserSessionManager(){}
    public static UserSessionManager getInstance(){
        if(mInstance == null){
            synchronized (UserSessionManager.class){
                if(mInstance == null){
                    mInstance = new UserSessionManager();
                }
            }
        }
        return mInstance;
    }

    private ConcurrentHashMap<Integer,Long> mUserSession = new ConcurrentHashMap<>();

    public void addUserSession(Integer userId,Long sessionId){
        mUserSession.put(userId,sessionId);
    }

    public void removeUserSession(Long sessionId){
        Map.Entry del = null;
        for(Map.Entry entry : mUserSession.entrySet()){
            if(entry.getValue() == sessionId){
                del = entry;
                break;
            }
        }
        if(del != null) {
            mUserSession.remove(del.getKey(),del.getValue());
        }
    }

    public Long getSessionId(Integer userId){
        return mUserSession.get(userId);
    }

}
